package io.xxx.omni.oss.common

import com.google.gson.JsonElement
import com.google.gson.JsonObject
import java.time.LocalDateTime
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter
import java.util.*

fun Number?.format(): String? {
    if (this == null) {
        return null
    }
    return numberFormat.format(this)    // #,##0.00
}

fun LocalDateTime.format(): String {
    return this.format(dateTimeFormatter)   // yyyy-MM-dd HH:mm:ss
}

fun OffsetDateTime.format(): String {
    return this.format(dateTimeFormatter)   // yyyy-MM-dd HH:mm:ss
}

fun Date?.format(): String? {
    if (this == null) {
        return null
    }
    return dateFormat.format(this)  // yyyy-MM-dd HH:mm:ss
}

fun String.toLocalDateTime(formatter: DateTimeFormatter = dateTimeFormatter): LocalDateTime {
    return LocalDateTime.parse(this, formatter)
}

fun Long.toLocalDateTime(): LocalDateTime {
    return LocalDateTime.ofEpochSecond(this / 1000, (this % 1000).toInt(), zoneOffset)
}

fun Date.toLocalDateTime(): LocalDateTime {
    return LocalDateTime.ofInstant(this.toInstant(), zoneOffset)
}

fun JsonElement.toLocalDateTime(): LocalDateTime {
    return LocalDateTime.parse(this.asString, dateTimeFormatter)
}

fun Any.toJsonString(): String {
    return when (this) {
        is String -> this
        else -> gson.toJson(this)
    }
}

fun Any.toJsonObject(): JsonObject {
    return when (this) {
        is String -> gson.fromJson(this, JsonObject::class.java)
        else -> gson.fromJson(gson.toJson(this), JsonObject::class.java)
    }
}